package com.example.redislock;

import redis.clients.jedis.Jedis;

public class PostponeTask implements Runnable {

    private String key;
    private String value;
    private long expireTime;
    private boolean isRunning;
    private RedisDistributeLock redisDistributeLock;
    private Jedis jedis;

    public PostponeTask() {
    }

    public PostponeTask(String key, String value, long expireTime, boolean isRunning, RedisDistributeLock redisDistributeLock, Jedis jedis) {
        this.key = key;
        this.value = value;
        this.expireTime = expireTime;
        this.isRunning = isRunning;
        this.redisDistributeLock = redisDistributeLock;
        this.jedis = jedis;
    }

    @Override
    public void run() {
        //线程等待剩余20%时间后执行延时
        long waitTime = expireTime * 4 / 5;
        while (isRunning) {
            try {
                Thread.sleep(waitTime);
                if (redisDistributeLock.postpone(jedis,key, value, expireTime)) {
                    System.out.println("延时成功.........");
                } else {
                    this.stop();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void stop() {
        this.isRunning = false;
    }
}
